<?php
class Timesheet extends CI_Model {

	/*
	 * get timesheet
	 */
	function getTimesheet(){
		$params = json_decode($_POST['params']);
		$query = $this->db->get_where('timesheets', array(
			'year' => $params->year,
			'month' => $params->month,
			'id_user' => $this->session->userdata['id_node']
		));
		return $query->result();
	}

	/*
	 * save timesheet
	 */
	function saveTimesheet(){
		$params = json_decode($_POST['params']);
		$days = json_encode($params->days);
		//check if exists
		$timesheetExists = $this->checkIfExists();
		if($timesheetExists){
			//update
			$data = array(
				'data' => $days,
				'date_updated' => date('Y-m-d H:i:s')
			);
			$this->db->where('id_timesheet', $timesheetExists[0]->id_timesheet);
			return $this->db->update('timesheets', $data);
		}
		else{
			//save
			$data = array(
				'id_user' => $this->session->userdata['id_node'],
				'year' => $params->year,
				'month' => $params->month,
				'data' => $days,
				'date_updated' => date('Y-m-d H:i:s')
			);
			return $this->db->insert('timesheets', $data);
		}
	}

	/*
	 * check if timesheet for month/yer exists
	 */
	function checkIfExists(){
		$params = json_decode($_POST['params']);

		$query = $this->db->get_where('timesheets', array(
			'year' => $params->year,
			'month' => $params->month,
			'id_user' => $this->session->userdata['id_node']
		));
		return $query->result();
	}
}